<template>
  <current>
    <div class="common-container center-container flex flex-col h-full">
      <div class="common-header"><h3 class="common-header-title">研究中心</h3></div>
      <div class="common-content flex flex-1 flex-col">
        <div class="m-b-20 flex-bc">
          <div class="flex flex-items-center">
            <div class="all-center mr-10 flex-shrink-0">
              <span class="font-bold">所有中心</span>
              <span class="total-num">{{ pageObj.total }}</span>
            </div>
            <search-input v-model="nameInput" placeholder="输入项目名称精确查询" @search="search" />
          </div>
          <div>
            <el-button type="primary" @click="add">添加中心</el-button>
            <el-button type="danger" :disabled="selectData.length === 0" @click="batchDel"
              >批量移除</el-button
            >
          </div>
        </div>

        <div class="table-wrap ym-box flex-1">
          <ym-table
            v-loading="tableLoading"
            select-show
            class="no-selected"
            :data="tableData"
            :column-data="columnData"
            @selection-change="changeSelection"
          >
            <template #operator="{ row }">
              <div class="operator-list">
                <el-icon @click="edit(row)">
                  <Edit />
                </el-icon>
                <el-icon @click="del(row)" class="remove">
                  <Close />
                </el-icon>
              </div>
            </template>
          </ym-table>
          <pagination
            v-model:currentPage="pageObj.pageNum"
            v-model:pageSize="pageObj.pageSize"
            :total="pageObj.total"
            @pagination="search"
          />
        </div>
      </div>
    </div>

    <dialog-view
      v-model:visible="dialogVisible"
      :title="dialogTitle"
      :save-loading="saveLoading"
      @cancel="cancel"
      @confirm="confirm"
      @close="close"
      :width="800"
    >
      <el-form ref="formRef" :model="form" label-width="120px">
        <div class="center-list">
          <div class="flex" v-for="(center, index) in form.centers" :key="center._id">
            <el-form-item
              label="研究中心"
              :prop="'centers.' + index + '.oid'"
              :rules="{
                required: true,
                message: '请选择研究中心',
                trigger: 'change',
              }"
            >
              <select-form
                v-model="center.oid"
                :options="stationOptions"
                :multiple="false"
                :default-props="{ label: 'name', value: 'oid' }"
              />
            </el-form-item>
            <el-form-item
              label="计划收集例数"
              :prop="'centers.' + index + '.gatherPlan'"
              :rules="{
                required: true,
                message: '请输入计划收集例数',
                trigger: 'blur',
              }"
            >
              <el-input v-model="center.gatherPlan" />
            </el-form-item>
            <div
              class="mb-[18px] ml-[10px] color-[--el-color-danger] flex cursor-pointer flex-items-center @hover:color-[--el-color-danger-light-3]"
            >
              <el-icon class="font-size-[18px]" @click="removeCenter(index)"><Remove /></el-icon>
            </div>
          </div>
        </div>
        <div class="pl-[120px] mt-[20px]">
          <el-button round size="small" @click="addCenter"
            ><el-icon class="mr-[5px]"><Plus /></el-icon>添加研究中心</el-button
          >
        </div>
      </el-form>
    </dialog-view>
  </current>
</template>

<script lang="ts" setup>
import { reactive, Ref, ref, toRefs } from 'vue'
import { useRoute } from 'vue-router'

import SearchInput from '@/components/CommonSearch/SearchInput/index.vue'
import SelectForm from '@/components/Form/Select.vue'
import Current from '../../current/index.vue'

import OrgApi from '@/api/backend/organization'
// import ProjectApi from '@/api/project'
import StationApi from '@/api/project/station'

// import { parseTime } from '@/utils/time'
import { commonHandle, DialogView, Pagination, YmTable } from '@/views/mixins/common'
import IBaseObj from '#/index'
import type { FormInstance } from 'element-plus'
import { nanoid } from 'nanoid'

const { pid } = useRoute().query

const { state, handleSearch, handleDelete, handleAdd, handleEdit, handleCancel, handleConfirm } =
  commonHandle()

const { pageObj, tableData, tableLoading, dialogVisible, dialogTitle, isAdd, saveLoading } =
  toRefs(state)

const columnData = [
  {
    label: '中心编号',
    prop: 'oid',
  },
  {
    label: '中心名称',
    prop: 'name',
  },
  {
    label: '计划收集例数',
    prop: 'gatherPlan',
  },
  {
    label: '已收集例数',
    prop: 'gatherFinish',
  },
]

const nameInput = ref('')
const search = () => {
  handleSearch(StationApi.queryStation, { pid, name: nameInput })
}

search()

const selectData: Ref<any[]> = ref([])
const changeSelection = (newSelection: any[]) => {
  selectData.value = newSelection
}
const batchDel = () => {
  console.log('s', selectData.value)
}

const add = () => {
  handleAdd('添加研究中心')
}
const edit = (row: IBaseObj) => {
  console.log(row)
  // handleEdit('编辑研究中心')
}
const del = (row: IBaseObj) => {
  console.log(row)
  handleDelete({
    url: StationApi.delUrl,
    id: row.id,
    message: '确定移除该中心？',
    success: search,
  })
}

const formRef = ref<FormInstance>()
const form = reactive({
  centers: [
    {
      _id: nanoid(),
      oid: '',
      gatherPlan: '',
    },
  ],
})

const cancel = () => {
  handleCancel()
}

const confirm = () => {
  formRef.value?.validate((valid: boolean) => {
    const params = form.centers.map((v) => {
      return { ...v, pid }
    })

    handleConfirm({
      valid,
      addApi: StationApi.batchSaveStation,
      params: { stations: params },
      cb: () => {
        search()
        getStationOptions()
      },
    })
  })
}
const close = () => {
  formRef.value?.clearValidate()
  form.centers = [
    {
      _id: nanoid(),
      oid: '',
      gatherPlan: '',
    },
  ]
}

const addCenter = () => {
  form.centers.push({
    _id: nanoid(),
    oid: '',
    gatherPlan: '',
  })
}
const removeCenter = (index: number) => {
  form.centers.splice(index, 1)
}

const stationOptions = ref<IBaseObj[]>([])
const getStationOptions = async () => {
  const ret = await OrgApi.getOrgStationList(pid as string)
  stationOptions.value = ret || []
}
getStationOptions()
</script>

<style lang="scss" scoped>
.all-center {
  .total-num {
    position: relative;
    top: -4px;
    display: inline-block;
    height: 17px;
    margin-top: -5px;
    margin-left: 5px;
    line-height: 16px;
    padding: 1px 5px;
    border-radius: 50%;
    font-size: 12px;
    background-color: rgba(0, 0, 0, 0.07);
    color: #707070;
    text-align: center;
    vertical-align: baseline;
  }
}
.operator-list {
  display: flex;
  align-items: center;
  font-size: 18px;

  & > * {
    margin-right: 5px;
    cursor: pointer;

    &:hover {
      color: var(--color-primary);
    }
  }

  .remove {
    color: var(--el-color-danger);

    &:hover {
      color: var(--el-color-danger-light-3);
    }
  }

  svg {
    outline: none;
  }
}
.common-content {
  padding: 20px 0 0;
}
.common-card {
  padding: 16px;
  border: 1px solid #e5e5e5;
  background-color: #fafafa;
}
.org-member {
  margin-top: 20px;

  h4 {
    margin: 10px 0;
  }

  .common-card {
    padding: 0 0 16px;
  }

  .card-title {
    padding: 6px 16px;
    line-height: 36px;
    background-color: #fafafa;
    border-bottom: 1px solid #e5e5e5;
  }

  .total-num {
    position: relative;
    top: -4px;
    display: inline-block;
    height: 17px;
    margin-top: -5px;
    margin-left: 5px;
    line-height: 16px;
    padding: 1px 5px;
    border-radius: 50%;
    font-size: 12px;
    background-color: rgba(0, 0, 0, 0.07);
    color: #707070;
    text-align: center;
    vertical-align: baseline;
  }
}

.member-list {
  li {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 10px 16px;
    border: 1px solid #f0f0f0;
    font-size: 14px;
    color: #2e2e2e;
    word-break: break-word;
  }
}

.org-info {
  line-height: 1.4;
  .name {
    margin-right: 4px;
    font-weight: bold;
  }

  .time {
    font-size: 12px;
  }
}

.right-operator {
  display: flex;
  align-items: center;
}

.bold {
  font-weight: bold;
}
</style>
